package com.aiyige.page.photo;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.eventbus.EventPhotoTap;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.page.photo.adapter.PhotoDataPageAdapter;
import com.aiyige.page.photo.model.Photo;
import com.aiyige.page.photo.model.PhotoDetail;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.UIHelper;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.vondear.rxtools.RxTextTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterConfig.PhotoPage)
public class PhotoPage extends AppCompatActivity {
    @BindView(R.id.mainVp)
    PhotoViewPager mainVp;
    @BindView(R.id.introductionTv)
    TextView introductionTv;
    @BindView(R.id.photoHeadLayout)
    View photoHeadLayout;
    @Autowired
    PhotoDetail photoDetail = null;
    PhotoDataPageAdapter photoDataPageAdapter;
    @BindView(R.id.downloadBtn)
    ImageView downloadBtn;
    volatile boolean showOverlay;
    volatile boolean animating;
    @BindView(R.id.finishBtn)
    ImageView finishBtn;
    @BindView(R.id.detailLayout)
    RelativeLayout detailLayout;
    int total = 0;
    int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_photo);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        showOverlay = true;
        animating = false;
        if (photoDetail == null || ListUtil.isEmpty(photoDetail.getPhotoList())) {
            finish();
            return;
        } else {
            photoDetail.setPlayIndex(Math.max(0, Math.min(photoDetail.getPlayIndex(), photoDetail.getPhotoList().size())));
        }
        total = photoDetail.getPhotoList().size();
        index = photoDetail.getPlayIndex();
        downloadBtn.setVisibility(photoDetail.isLocalPhoto() ? View.INVISIBLE : View.VISIBLE);
        photoDataPageAdapter = new PhotoDataPageAdapter(getSupportFragmentManager(), photoDetail);
        mainVp.setAdapter(photoDataPageAdapter);
        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                index = position;
                updateIntroduction();
                updateDownloadBtn();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mainVp.setCurrentItem(index, false);
        updateIntroduction();
        updateDownloadBtn();
        EventBus.getDefault().register(this);
    }

    public void updateDownloadBtn() {
        Photo photo = photoDetail.getPhotoList().get(index);
        if (photo.getMediaType() == Photo.MEDIA_TYPE_PHOTO && !photoDetail.isLocalPhoto()) {
            downloadBtn.setVisibility(View.VISIBLE);
        } else {
            downloadBtn.setVisibility(View.INVISIBLE);
        }


    }

    public void updateIntroduction() {
        String introduction = photoDetail.getPhotoList().get(index).getIntroduction();
        if (TextUtils.isEmpty(introduction)) {
            introduction = "";
        }
        RxTextTool.getBuilder("")
                .append(String.valueOf(index + 1)).setProportion(1.125f).setItalic()
                .append(" / ").setProportion(0.6875f)
                .append(String.valueOf(total)).setProportion(0.8125f)
                .append("  ")
                .append(introduction)
                .into(introductionTv);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        UIHelper.setSystemUIVisibility(this, newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            UIHelper.setSystemUIVisibility(this, getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE);
        }
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventPhotoTap(EventPhotoTap event) {
        showOverlay = !showOverlay;
        if (showOverlay) {
            showOverlay();
        } else {
            hideOverlay();
        }
    }

    public void showOverlay() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 1f);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                finishBtn.setAlpha(alpha);
                downloadBtn.setAlpha(alpha);
                photoHeadLayout.setAlpha(alpha);
                detailLayout.setAlpha(alpha);
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                finishBtn.setAlpha(0f);
                downloadBtn.setAlpha(0f);
                detailLayout.setAlpha(0f);
                photoHeadLayout.setAlpha(0f);
                finishBtn.setVisibility(View.VISIBLE);
                downloadBtn.setVisibility(photoDetail.isLocalPhoto() || photoDetail.getPhotoList().get(index).getMediaType() == Photo.MEDIA_TYPE_VIDEO ? View.INVISIBLE : View.VISIBLE);
                detailLayout.setVisibility(View.VISIBLE);
                photoHeadLayout.setVisibility(View.VISIBLE);
                animating = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                animating = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                animating = false;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        valueAnimator.start();

    }

    public void hideOverlay() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(1f, 0f);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                finishBtn.setAlpha(alpha);
                downloadBtn.setAlpha(alpha);
                detailLayout.setAlpha(alpha);
                photoHeadLayout.setAlpha(alpha);
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                animating = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                finishBtn.setVisibility(View.INVISIBLE);
                downloadBtn.setVisibility(View.INVISIBLE);
                detailLayout.setVisibility(View.INVISIBLE);
                photoHeadLayout.setVisibility(View.INVISIBLE);
                animating = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                animating = false;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        valueAnimator.start();
    }

    @OnClick({R.id.downloadBtn, R.id.finishBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.downloadBtn:
                DownloadUtil.downloadPhoto(this, photoDetail.getPhotoList().get(mainVp.getCurrentItem()).getUrl());
                break;
            case R.id.finishBtn:
                finish();
                break;
        }
    }
}
